/**
 * @ProjectName:Backend
 * @Title: TengXunSmsUtils
 * @Package com.phrp.util.TenxunSms
 * @Description: 腾讯短信云服务工具类
 * @author SuShuChao
 * @date 2024/5/7 17:15
 * @version V1.0
 * Copyright (c) 2024, 2034279227@qq.com All Rights Reserved.
 */
package com.phrp.util.tengXunSms;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

@Component
public class TengXunSmsUtils {

    @Value("${sms.secretId}")
    private String secretId;

    @Value("${sms.secretKey}")
    private String secretKey;

    @Value("${sms.sdkAppId}")
    private String smsSdkAppId;

    private final String smsSign = "神奇的梦无忧公众号";

    @Value("${sms.templateId}")
    private String templateId;

    @Value("${sms.expireTime}")
    private String expireTime;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public String sendSms(String phone) {
        try {
            Credential cred = new Credential(secretId, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            SmsClient client = new SmsClient(cred, "", clientProfile);

            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppid(smsSdkAppId);
            req.setSign(smsSign);

            req.setPhoneNumberSet(new String[]{"86" + phone});
            req.setTemplateID(templateId);

            Random random = new Random();
            int i = random.nextInt(899999) + 100000;

            req.setTemplateParamSet(new String[]{String.valueOf(i),expireTime});

            SendSmsResponse res = client.SendSms(req);

            // 判断短信发送是否成功
            if (res != null && res.getSendStatusSet() != null) {
                for (SendStatus sendStatus : res.getSendStatusSet()) {
                    if ("Ok".equalsIgnoreCase(sendStatus.getCode())) {
                        // 短信发送成功
                        Logger.getLogger("SmsLog").info("短信发送成功，手机号：" + sendStatus.getPhoneNumber());
                        // 存入redis中
                        redisTemplate.opsForValue().set(phone, String.valueOf(i), Integer.valueOf(expireTime), TimeUnit.MINUTES);
                        return "true";
                    } else {
                        // 短信发送失败
                        Logger.getLogger("SmsLog").warning("短信发送失败，手机号：" + sendStatus.getPhoneNumber() + "，错误码：" + sendStatus.getCode() + "，错误信息：" + sendStatus.getMessage());
                        return "false";
                    }
                }
                return "false";
            } else {
                // 未获取到发送状态信息
                Logger.getLogger("SmsLog").warning("未获取到发送状态信息");
                return "false";
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            // 发送短信过程中出现异常
            Logger.getLogger("SmsLog").severe("发送短信异常：" + e.getMessage());
            return "false";
        }
    }
}
